#include "enemy.h"
#include <player.h>
#include"bullet.h"
#include <QPixmap>
#include "GameSetting.h"
#include <QGraphicsScene>
#include <QKeyEvent>
#include <QRandomGenerator>
#include "score.h"
#include "health.h"
using namespace GameSetting;
Enemy::Enemy(QGraphicsItem *parent ):QGraphicsPixmapItem(parent){
    setPixmap(QPixmap(":/image/EnemyPlane.png"));
    //缩放
    setScale(EnemyScale);
    //位置
    int max = SceneWidth-boundingRect().width()*EnemyScale;
    int randomNumber = QRandomGenerator::global()->bounded(1,max);
    setPos(randomNumber,0);
    //可以获取焦点   并获取焦点
    setFlag(QGraphicsItem::ItemIsFocusable);
    setFocus();
    startTimer(EnemyTimer);

}


void Enemy::timerEvent(QTimerEvent *)
{
    //碰撞检测
    QList<QGraphicsItem*> collidingItems = this->collidingItems();
    for(auto item:collidingItems){
        if(typeid(*item)==typeid(Player)){
            //健康值减少
            Health::getInstance().decrease();
            scene()->removeItem(this);
            delete this;
            return;
        }
        if(typeid(*item)==typeid(Bullet)){
            //需要加分
            Score::getInstance().increase();
            scene()->removeItem(item);
            delete item;
            scene()->removeItem(this);
            delete this;
            return;
        }
    }
    setPos(x(),y()+EnemySpeed);
    if(y()>SceneHeight){
        scene()->removeItem(this);
        delete this;
        return;
    }
}
